/**
 * 后台管理子路由 admin
 */
const Router = require('koa-router');
let admin = new Router();
const {fileUpload} = require('../utils/FileUploadDownload');
const { getJSONAllData, getJSONDataTotal, getJSONByPagination,
    getJSONById, getJSONByUsername, getJSONByKeys, addJsonFile,
    updateJsonById, getJSONByCondition, getAllJSONByCondition  } = require('../utils/JsonFile');
const JwtUtil = require('../utils/jwt');
const { TimeFormat } = require('../utils/TimeFormat');
const getIpAddress= require('../utils/getIPAddress')

admin.use(async (ctx, next) => {
    // console.log(ctx.request);
    let url= ctx.request.url;
    // console.log(url)
    // 把登陆和注册请求去掉了，其他的请求都需要进行token校验
    if (url.search(/^\/admin\/login/i)===-1 && url !== '/admin/register') {
        let token = ctx.request.header['authorization'];
        let jwt = new JwtUtil(token);
        let result = jwt.verifyToken();

        // 如果考验通过就next，否则就返回登陆信息不正确
        if (result === 'error') {
            ctx.body = {
                status: 403,
                msg: '登录已过期,请重新登录'
            };
        } else {
            await next();
        }
    } else {
        await next();  // 注意：因为下方路由使用了async await，所以这里也要加async await
    }
});

admin.get('/login', async ctx=>{
    let { username, password }= ctx.query;
    let result= {};
    try {
        result= await getJSONByUsername('user.json', username);
    } catch (e) {
        result.code = 500;
    }
    if(result.code===200) {
        let data= JSON.parse(result.data);
        if(data.password===password) {
            await addJsonFile('log.json', {
                time: TimeFormat(Date.now()),
                username: data.username,
                operation: '登录',
                IP: getIpAddress()
            });
            let jwt= new JwtUtil(username);
            let token= jwt.generateToken();
            ctx.body= {
                code: 200,
                msg: '登录成功',
                data: {
                    username: data.username,
                    userId: data.id,
                    token: token,
                    avatar: data.avatar
                }
            }
        } else {
            ctx.body= {
                code: 201,
                msg: '登录失败'
            };
        }
    } else {
        ctx.body= {
            code: 201,
            msg: '登录失败'
        };
    }
}).post('/register', async ctx=>{
    let { username, phone, email, password }= ctx.request.body;
    let res={};
    try {
        res= await getJSONByKeys('user.json', ['username', 'phone', 'email'], [username, phone, email]);
    } catch (e) {
        res.code = 500;
    }
    if(res.code===202) {
        ctx.body= res;
        return ;
    }

    let params= {
        id: Date.now(),
        username,
        phone,
        email,
        password,
        avatar: '/upload/avatar.png'
    };
    let result= await addJsonFile('user.json', params);
    if(result.code===200) {
        await addJsonFile('log.json', {
            time: TimeFormat(Date.now()),
            username: username,
            operation: '注册',
            IP: getIpAddress()
        });

        let jwt= new JwtUtil(username);
        let token= jwt.generateToken();
        ctx.body= {
            code: 200,
            msg: '注册成功',
            data: {
                username,
                userId: params.id,
                token: token,
                avatar: '/upload/avatar.png'
            }
        }
    } else {
        ctx.body= {
            code: 201,
            msg: '注册失败'
        };
    }
}).get('/getUserInfo/:id', async ctx=>{
    let userId= ctx.params.id;
    let result= await getJSONById('user.json', userId);
    ctx.body= result;
})


admin.get('/home', async (ctx) => {
    ctx.body = "Home index";
}).get('/getDataNum', async (ctx) => {
    let typeNumResult= await getJSONDataTotal('types.json');
    let articleNumResult= await getJSONDataTotal('article.json');
    if(typeNumResult.code===200 && articleNumResult.code===200) {
        ctx.body = {
            code: 200,
            msg: '数据查询成功',
            data: {
                typeNum: typeNumResult.data.total,
                articleNum:  articleNumResult.data.total
            }
        };
    } else {
        ctx.body = {
            code: 201,
            msg: '数据查询失败'
        };
    }
});

admin.post('/addArticle', async ctx=>{
    let { title, type, intro, content }= ctx.request.body;
    let coverImg= ctx.request.files.file;
    let fileUploadResult= null;
    if(coverImg) {
        fileUploadResult= await fileUpload(coverImg);
        console.log(fileUploadResult);
    }
    let params= {
        id: Date.now(),
        title,
        type,
        intro,
        content,
        isHot: false,
        isPublish: true,
        time: TimeFormat(Date.now()),
        views: 0
    }
    if(fileUploadResult && !fileUploadResult.status) {
        params.coverImg= '/upload/' + fileUploadResult.filename;
    } else {
        params.coverImg= '/upload/avatar.png';
    }

    let addResult= await addJsonFile('article.json', params);
    if(addResult.code===200) {
        ctx.body = {
            code: 200,
            msg: '文章暂存成功',
            data: {
                id: params.id
            }
        }
    } else {
        ctx.body= addResult;
    }
}).post('/saveArticle', async ctx=>{
    let { title, type, intro, content }= ctx.request.body;
    let coverImg= ctx.request.files.file;
    let fileUploadResult= null;
    if(coverImg) {
        fileUploadResult= await fileUpload(coverImg);
        console.log(fileUploadResult);
    }
    let params= {
        id: Date.now(),
        title,
        type,
        intro,
        content,
        isHot: false,
        isPublish: false,
        time: TimeFormat(Date.now()),
        views: 0
    }
    if(fileUploadResult && !fileUploadResult.status) {
        params.coverImg= '/upload/' + fileUploadResult.filename;
    } else {
        params.coverImg= '/upload/avatar.png';
    }

    let addResult= await addJsonFile('article.json', params);
    if(addResult.code===200) {
        ctx.body = {
            code: 200,
            msg: '文章暂存成功',
            data: {
                id: params.id
            }
        }
    } else {
        ctx.body= addResult;
    }
}).get('/getArticleList', async ctx=>{
    let { currPage, pageSize } = ctx.request.query;
    let result= await getJSONByPagination('article.json', currPage, pageSize );
    ctx.body = result;
}).post('/updateHotById', async ctx=>{
    let { id, isHot } = ctx.request.body;
    console.log(id, isHot)
    let updateResult= await updateJsonById('article.json', id, { 'isHot': isHot});
    ctx.body = updateResult;
}).post('/updatePublishById', async ctx=>{
    let { id, isPublish } = ctx.request.body;
    let updateResult= await updateJsonById('article.json', id, { 'isPublish': isPublish});
    ctx.body = updateResult;
}).post('/updateArticleById', async ctx=>{
    let params = ctx.request.body;
    let coverImg= ctx.request.files.file;
    let fileUploadResult= null;
    if(coverImg) {
        fileUploadResult= await fileUpload(coverImg);
        console.log(fileUploadResult);
    }
    if(fileUploadResult && !fileUploadResult.status) {
        params.coverImg= '/upload/' + fileUploadResult.filename;
    }
    params.time = TimeFormat(Date.now());

    let updateResult= await updateJsonById('article.json', params.id, params);
    ctx.body = updateResult;
}).get('/search', async ctx=>{
    let { type, isHot, currPage=1, pageSize=6 } = ctx.request.query;
    let params= {};
    if(typeof type !=='undefined') params.type= type;
    if(typeof isHot !=='undefined') params.isHot= JSON.parse(isHot);
    let result= await getJSONByCondition('article.json', params, currPage, pageSize);
    ctx.body = result;
});




admin.get('/getTypeList', async ctx=>{
    let result= await getJSONAllData('types.json');
    ctx.body= result;
}).post('/addType', async ctx=>{
    let {name, value} = ctx.request.body;
    let result= await addJsonFile('types.json', {
        id: Date.now(),
        name,
        value
    });
    ctx.body= result;
});


admin.get('/getLogInfoList', async ctx=>{
    let { currPage, pageSize } = ctx.request.query;
    let result= await getJSONByPagination('log.json', currPage, pageSize );
    ctx.body = result;
}).get('/getLastLogTime', async ctx=>{
    let result= await getAllJSONByCondition('log.json', {}, 1);
    if(result.code===200) {
        ctx.body = {
            code: 200,
            data: JSON.parse(result.data)[0].time
        };
    } else {
        ctx.body= result;
    }
});


admin.post('/updateAccountInfo', async ctx=>{
    // console.log(ctx.request.body)    // 用这个解析json和urlencoded
    // console.log(ctx.request.files);  // 用这个解析文件
    let { id, password }= ctx.request.body;
    let avatar= ctx.request.files.file;
    // console.log(password, avatar);
    let fileUploadResult= null;
    if(avatar) {
        fileUploadResult= await fileUpload(avatar);
        // console.log(fileUploadResult);
    }

    let params= {};
    if(password) params['password']= password;
    if(fileUploadResult && !fileUploadResult.status) params.avatar= '/upload/' + fileUploadResult.filename;

    let updateResult= await updateJsonById('user.json', id, params);
    if(updateResult.code===200) {
        let userInfo= await getJSONById('user.json', id);
        ctx.body = userInfo
    } else {
        ctx.body = updateResult;
    }
});





module.exports = admin;
